﻿using System;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Threading;

namespace Ajax.Web.Install
{
    public partial class Step : System.Web.UI.Page
    {
        protected string installInfo = string.Empty;
        protected bool showbutton = true;
        protected override void OnLoad(EventArgs e)
        {
            string str = base.Server.MapPath("db/");
            string path = str + "sqlserverinstall.lock";
            string str3 = str + "Ajax.sql";
            if (File.Exists(path))
            {
                base.Response.Write("请先使用FTP删除掉db目录下的sqlserverinstall.ok文件在进行安装");
                base.Response.End();
            }
            else
            {
                this.installInfo = "请确保站点目录有来宾账号的读取权限，users组账号的修改权限";
                string str4 = base.Server.MapPath("~/testdirect");
                string str5 = base.Server.MapPath("~/testfile.txt");
                try
                {
                    if (Directory.Exists(str4))
                    {
                        Directory.Delete(str4);
                    }
                    Directory.CreateDirectory(str4);
                    Directory.Delete(str4);
                    File.WriteAllText(str5, "test");
                    File.Delete(str5);
                    this.installInfo = this.installInfo + "<br>";
                }
                catch
                {
                    this.installInfo = this.installInfo + "<span style='color:#FF0000;'>失败,没有权限</span><br>";
                    this.showbutton = false;
                }
                if (this.Page.IsPostBack)
                { 
                    string str6 = base.Request["host"];
                    string str7 = base.Request["user"];
                    string str8 = base.Request["pass"];
                    string str9 = base.Request["name"];
                    if ((((str6 == string.Empty) || (str7 == string.Empty)) || (str8 == string.Empty)) || (str9 == string.Empty))
                    {
                        this.SetError("您输入的信息不完整，请重试");
                    }
                    else
                    {
                        bool flag = true;
                        string connectionString1 = string.Format("server={0};database={1};uid={2};pwd={3}", new object[] { str6, "master", str7, str8 });
                        SqlConnection connection1 = new SqlConnection(connectionString1);
                        try
                        {
                            connection1.Open();
                            if (this.checkcreatedb.Checked == true)
                            {
                                SqlCommand command1 = new SqlCommand("create database " + str9, connection1);
                                command1.ExecuteNonQuery();
                                Thread.Sleep(1000);
                            }
                            else
                            {
                                this.SetError("创建数据库失败，请检查是否已存在相同名称");
                            }
                        }
                        catch
                        {
                            connection1.Close();
                        }
                        finally
                        {
                            connection1.Close();
                        }
                        string connectionString = string.Format("server={0};database={1};uid={2};pwd={3}", new object[] { str6, str9, str7, str8 });
                        using (SqlConnection connection = new SqlConnection(connectionString))
                        {
                            string str11 = string.Empty;
                            try
                            {
                                str11 = "数据库连接失败";
                                connection.Open();
                                str11 = "当前数据库用户没有权限创建表";
                                SqlCommand command = new SqlCommand("IF EXISTS (SELECT name FROM sysobjects WHERE name = 'a' AND type = 'U')DROP table a;create table a(id int not null default 0);drop table a;", connection);
                                command.ExecuteNonQuery();
                                str11 = "数据库配置文件读取失败，可能没有读取权限。请确认Web.config拥有users组的修改权限";
                                XmlDocument document = new XmlDocument();
                                document.Load(base.Server.MapPath("~/Web.config"));
                                XmlNode node = document.SelectSingleNode("//configuration/connectionStrings/add[@name='Sqlserverconstring']");
                                if (node != null)
                                {
                                    node.Attributes["connectionString"].Value = connectionString;
                                }
                                else
                                {
                                    this.SetError("安装错误");
                                    return;
                                }
                                str11 = "数据库配置文件写入失败，可能没有写入权限。请确认Web.config拥有users组的修改权限";
                                document.Save(base.Server.MapPath("~/Web.config"));
                                str11 = "数据库安装文件读取失败";
                                string str12 = File.ReadAllText(str3, Encoding.UTF8);
                                string[] separator = new string[] { "\r\n;" };  
                                string[] strArray2 = str12.Split(separator, StringSplitOptions.RemoveEmptyEntries);
                                str11 = "数据库安装失败";
                                for (int i = 0; i < strArray2.Length; i++)
                                {
                                    command = new SqlCommand(strArray2[i], connection);
                                    str12 = strArray2[i];
                                    command.ExecuteNonQuery();
                                }
                                File.WriteAllText(path, "删除此文件就能安装啦");
                                string str13 = base.Server.MapPath("~/bin/sqlserverinstall.lock");
                                File.WriteAllText(str13, "ok");
                                File.Delete(str13);
                            }
                            catch (Exception exception)
                            {
                                flag = false;
                                this.SetError(str11 + "<br>" + exception.Message);
                            }
                            finally
                            {
                                connection.Close();
                            }
                        }
                        if (flag)
                        {
                            base.Response.Redirect("~/Index.html");
                            base.Response.End();
                        }
                    }
                }
            }
        }

        public void SetError(string errtext)
        {
            this.installInfo = errtext;
        }
    }
}
